<?php
namespace app\common\model\member;

use app\common\model\BaseModel;
use think\Db;

class ChangeLogModel extends BaseModel
{
    protected $name = 'member_change_log';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 搜索器
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchViewAttr($query, $value, $data){
        //主表
        if(in_array('member_change_log',$value)){
            $fields = $this->getTableFields('member_change_log');
            $query->view('member_change_log',$fields);
        }
        //关联表
        if(in_array('member',$value)){
            $query->view('member','username,nickname,mobile,email,qq','member_change_log.member_id=member.id','LEFT');
        }
    }

    /**
     * 变动
     */
    public function change($memberId,$change,$changeType,$changeDesc){
        //插入账户变动记录
        $changeData = [
            'member_id'=>$memberId,
            'change_type'=>$changeType,
            'change_desc'=>$changeDesc,
            'change_time'=>time(),
        ];
        $memberData=[];
        if(isset($change['points']) && $change['points']!=0){
            $changeData['change_points']=$change['points'];
            $memberData['points']=Db::raw("points+{$change['points']}");
        }
        if(isset($change['frozen_points']) && $change['frozen_points']!=0){
            $changeData['change_frozen_points']=$change['frozen_points'];
            $memberData['frozen_points']=Db::raw("frozen_points+{$change['frozen_points']}");
        }
        if(isset($change['amount']) && $change['amount']!=0){
            $changeData['change_amount']=$change['amount'];
            $memberData['amount']=Db::raw("amount+{$change['amount']}");
        }
        if(isset($change['frozen_amount']) && $change['frozen_amount']!=0){
            $changeData['change_frozen_amount']=$change['frozen_amount'];
            $memberData['frozen_amount']=Db::raw("frozen_amount+{$change['frozen_amount']}");
        }
        if(empty($memberData)) exception('变动金额不正确');
        self::create($changeData);
        //更新会员资金账户
        MemberModel::where('id',$memberId)->update($memberData);
    }
}